<?php
namespace App\Libs\wrapper;

use Illuminate\Support\Facades\DB;

class Organize extends Comm{
/////////////////////////////////////////////// 部门
////////////////////// 部门列表
	/**
	 * 组织列表--数据
	 * @param name 部门名称
	 * @Parma type 类型：1.部门、2.小组
	 */
	public function organize_list($data){
		$where = "1=1";
		//name 部门名称
		if(isset($data['name'])){
			$where .= " and `name` like '%{$data['name']}%'";
		}
		//tyep 类型：1.部门、2.小组
		if(isset($data['type'])){
			$where .= " and `type`={$data['type']}";
			if($data['type']==1){
			    //验证是否有所有部门权限
                $identity = 'department_all';
                //var_dump($data);die;
                $userId = $data['user_info']['Id'];
                $sqlPower = "select pr.*,xr.*
				       from xt_role_user_join xruj
				       left join (select xprj.role_id, xprj.power_id, xp.*
				                         from xt_powers_role_join xprj
				                         inner join xt_powers xp on xp.Id=xprj.power_id
                                      ) as pr on pr.role_id = xruj.role_id
                       left join xt_role xr on xr.Id = pr.role_id 
				       where xruj.user_id={$userId} and pr.identity = '{$identity}'
				       group by pr.power_id";
                $power_list = json_decode(json_encode(db::select($sqlPower)), true);
                if (empty($power_list)) {
                    $sql = "select organize_id,type
					from organizes_member
					where user_id={$userId}";
                    $departmentList = json_decode(json_encode(db::select($sql)),true);
                    if(!empty($departmentList[0]['organize_id'])){
                        $where .= " and `Id` = {$departmentList[0]['organize_id']}";
                    }
                    $return['type'] = 2;
                    //var_dump($departmentList);die;
                }
            }else{
			    $return['type'] = 1;
            }
		}
		$where .= " and state=1";
		
		//分页
		$limit = "";
		if((!empty($data['page'])) and (!empty($data['page_count']))){
			$limit = " limit ".($data['page']-1)*$data['page_count'].",{$data['page_count']}";
		}
		
		$sql = "select SQL_CALC_FOUND_ROWS *
					from organizes
					where {$where} {$limit}";
		$list = json_decode(json_encode(db::select($sql)),true);
		
		//// 总条数
		if(isset($data['page']) and isset($data['page_count'])){
			$total = db::select("SELECT FOUND_ROWS() as total");
			$return['total'] = $total[0]->total;
		}
		$return['list']=$list;
		return $return;
    }
	
	/**
	 * 新增组织
	 * @parma name 名称
	 * @param desc 说明
	 * @apram type 类型：1.部门、2.小组
	 */
	public function organize_add_depart($data){
		//唯一性
		$sql  = "select `Id`
					from organizes
					where `type`={$data['type']} and `name`='{$data['name']}'";
		$find = db::select($sql);
		if(!empty($find)){
			if($data['type'] == '1'){
				return '部门已存在';
			}else{
				return '小组已存在';
			}
		}
		
		//新增部门
		$field = "";
		$insert = "";
		$arr = array('name', 'desc', 'type');
		foreach ($data as $k=>$v){
			if(!empty($v)){
				if(in_array($k, $arr)){
					$field .= ",`{$k}`";
					$insert .= is_numeric($v) ? ",{$v}" : ",'{$v}'";
				}
			}
		}
		$field = substr($field, 1);
		$insert = substr($insert, 1);
		
		$sql = "insert into organizes({$field}) values ({$insert})";
		$add = db::insert($sql);
		if($add){
			return 1;
		}else{
			return '新增失败';
		}
	}
	
	/**
	 * 编辑组织
	 * @param Id 组织id
	 */
	public function organize_update($data){
		//唯一性
		$sql  = "select `Id`
					from organizes
					where `type`={$data['type']} and `Id`!={$data['Id']} and `name`='{$data['name']}'";
		$find = db::select($sql);
		if(!empty($find)){
			if($data['type'] == '1'){
				return '部门已存在';
			}else{
				return '小组已存在';
			}
		}
		
		$set = "";
		$arr = array('name', 'desc');
		foreach ($data as $k=>$v){
			if(!empty($v)){
				if(in_array($k, $arr)){
					$set .= ",`{$k}`=".( is_numeric($v) ? "{$v}" : "'{$v}'");
				}
			}
		}
		
		if(empty($set)){
			return '修改数据为空';
		}
		
		$set = substr($set, 1);
		$sql = "update organizes
					set {$set}
					where `Id` = {$data['Id']}";
		$update = db::update($sql);
		if($update !== false){
			return 1;
		}else{
			return '修改成功';
		}
	}
	
	/**
	 * 删除组织
	 * @param Id 组织id
	 */
	public function organize_del($data){
		//判断组织中是否有成员
		$sql = "select om.Id
		            from organizes_member om
		            left join users u on om.user_id=u.Id
		            where om.organize_id = {$data['Id']} and u.state=1";
		//var_dump($sql);die;
		$find = db::select($sql);
		if(!empty($find)){
			return '还有成员，不能删除';
		}
		
		$where = "1=1";
		//Id 组织id
		if(!empty($data['Id'])){
			$where .= " and o.`Id`={$data['Id']}";
		}
		
		if($where == "1=1"){
			return '删除条件为空';
		}
		/*$sql = "delete o, om
					from organizes o
					left join organizes_member om on om.organize_id = o.Id
					where {$where}";
		$del = db::delete($sql);*/
        $sql = "update organizes
					set state=2
					where `Id` = {$data['Id']}";
        $del = db::update($sql);
		if($del){
			return 1;
		}else{
			return '删除失败';
		}
	}
	
	/**
	 * 成员列表--数据
	 * @param organize_id 组织id
	 * @param page 页码
	 * @param number 每页条数
	 */
	public function member_list($data){
		$where = "1=1";
		//organize_id 组织id
		if(!empty($data['organize_id'])){
			$where .= " and om.organize_id={$data['organize_id']}";
		}
		//分页
		$limit = "";
		if((!empty($data['page'])) and (!empty($data['number']))){
			$limit = " limit ".($data['page']-1)*$data['number'].",{$data['number']}";
		}
        $userId = $data['user_info']['Id'];
		$sql = "select type 
		        from organizes_member 
		        where user_id={$userId} and organize_id={$data['organize_id']}";
        $type = json_decode(json_encode(db::select($sql)),true);
        //var_dump($type);die;
        if(!empty($type)){

                $return['id_type'] = $type[0]['type'];

        }
        $where .= " and state=1";
		
		$sql = "select SQL_CALC_FOUND_ROWS om.Id as om_id, om.organize_id, om.type as type_m, u.*, ifnull(r.role_name, '未绑定用色') as role_name
					from organizes_member om
					inner join users u on u.Id = om.user_id
					left join (select ruj.user_id, group_concat(distinct r.`name` order by r.Id asc separator ' | ') as role_name
				                         from xt_role_user_join ruj
				                         inner join xt_role r on r.Id = ruj.role_id
				                         group by ruj.user_id
				                  ) r on r.user_id = u.Id
					where {$where}
					order by om.type desc, om.Id desc {$limit}";
		$list = json_decode(json_encode(db::select($sql)),true);
		$return['list']=$list;
		if(isset($data['page']) and isset($data['number'])){
			////符合条件设备总数
			$count = db::select("SELECT FOUND_ROWS() as count");
			$return['count'] = $count[0]->count;
		}
		return $return;
	}
	
	/**
	 * 获取可新增成员列表--数据
	 * @logic：未加入组织用户
	 * @param organize_id 组织id
	 * @param account 账号
	 */
	public function user_data($data){
		$where = "om.Id is null and u.state=1";
		//account 账号
		if(!empty($data['account'])){
			$where .= " and u.account like '%{$data['account']}%'";
		}
		//分页
		$limit = "";
		if((!empty($data['page'])) and (!empty($data['page_count']))){
			$limit = " limit ".($data['page']-1)*$data['page_count'].",{$data['page_count']}";
		}
		
		$sql = "select SQL_CALC_FOUND_ROWS u.*
				       from users u
				       left join (select Id, user_id
				                     from organizes_member
				                     group by user_id
				                   ) om on om.user_id = u.Id
				       where {$where} {$limit}";
		$list = json_decode(json_encode(db::select($sql)),true);
		
		//// 总条数
		if(isset($data['page']) and isset($data['page_count'])){
			$total = db::select("SELECT FOUND_ROWS() as total");
			$return['total'] = $total[0]->total;
		}
		$return['list']=$list;
		return $return;
	}
	
	/**
	 * 新增成员
	 * @param organize_id 组织id
	 * @param user_ids 用户id  例如：1,2,3
	 */
	public function member_add($data){
		////获取组织成员
		$sql = "select *
					from organizes_member
					where organize_id={$data['organize_id']} and user_id in ({$data['user_ids']})";
		$member_list = json_decode(json_encode(db::select($sql)),true);
		$ids = array();
		foreach ($member_list as $k=>$v){
			$ids[] = $v['user_id'];
		}
		
		////新增组织成员
		$user_ids = explode(",", $data['user_ids']);
		if(empty($user_ids)){
			return 'user_ids为空';
		}
		$insert = "";
		foreach ($user_ids as $ka=>$va){
			if(!in_array($va, $ids)){
				$insert .= ",({$data['organize_id']}, {$va}, now())";
			}
		}
		if(empty($insert)){
			return '新增数据为空';
		}
		$insert = substr($insert, 1);
		$sql = "insert into organizes_member(`organize_id`, `user_id`, `create_time`) values {$insert}";
		$add = db::insert($sql);
		if($add){
			return 1;
		}else{
			return '新增失败';
		}
	}
	
	/**
	 * 编辑组织成员信息
	 * @param Id 组织成员id
	 */
	public function member_update($data){
		$set = "";
		//organize_id 组织id
		if(!empty($data['organize_id'])){
			$set .= ",`organize_id`={$data['organize_id']},`type`=1";

		}
		//type 成员类型：1.部门主管、2.组长 3.普通成员
		if(!empty($data['type'])){
			$set .= ",`type`={$data['type']}";
		}
		
		if(empty($set)){
			return '修改数据为空';
		}
		$set = substr($set, 1);
		//var_dump($data);die;
		$sql = "update organizes_member
					set {$set}
					where `Id`={$data['Id']}";
//		return $sql;
		$update = db::update($sql);
		if($update !== false){
			return 1;
		}else{
			return '修改失败';
		}
	}
	
	/**
	 * 移除成员
	 * @parma Id 组织id
	 */
	public function member_del($data){
		$sql = "delete
					from organizes_member
					where `Id`={$data['Id']}";
		$del = db::delete($sql);
		if($del){
			return 1;
		}else{
			return '移除失败';
		}
	}





}//